package registe.service;


import net.iharder.Base64;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import registe.dao.TUserInfoMapper;
import registe.dao.TUserMapper;
import registe.untill.baseUntill.Map_ObjectUntill;
import registe.untill.baseUntill.MessageUntill;
import registe.untill.baseUntill.RespCodeBody;
import registe.bean.TUser;

import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by zhoumeineng on 2018/1/24.
 * 注册实现类
 *
 */
@Service
public class UserImpl {
    @Autowired
    TUserMapper tUserMapper;


    @Autowired
    TUserInfoMapper tUserInfoMapper;

    /**
     *
     * 判断账号是否存在
     *
     *  */
    @Transactional
    public JSONObject just_PhoneNum_Exit(String phoneNum){
        try {
            Integer count = tUserMapper.selectePhoneNum(phoneNum);

            if (count>0) return MessageUntill.messageBody(null, RespCodeBody.RESP_REGISTE_ERROR_CODE.getRespCode(),RespCodeBody.RESP_REGISTE_ERROR_CODE.getRespDesc());
        }catch (Exception e){
            e.printStackTrace();
        }
        return MessageUntill.messageBody(null,RespCodeBody.RESP_SUCCED_CODE.getRespCode(),RespCodeBody.RESP_SUCCED_CODE.getRespDesc());
    }


    /**
     * 账号注册
     *
     * */
    @Transactional
    public JSONObject phoneNumRegist(TUser tUser,String termId){
        String pwd = tUser.getPassword();

        /**
         * 密码加密
         * */
        tUser.setPassword(Base64.encodeBytes(pwd.getBytes()));

        /**
         * 设置注册时间
         * */
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy:MM:dd HH:mm:SS");
        tUser.setCreattime(dateFormat.format(System.currentTimeMillis()));

        /**
         * 生成uId
         * */
        String uid = Base64.encodeBytes((tUser.getPhonenum()).getBytes());
        tUser.setUid(uid);

        /**
         * 插入数据库
         * 用户注册
         * */
        tUserMapper.insertUser(tUser);

        /**
         * 创建用户信息
         * */
        tUserInfoMapper.createUserInfo(uid);

        /**
         * 返回参数 attach
         * */
        Map attact = new HashMap();
        attact.put("uid",uid);
        return MessageUntill.messageBody(attact,RespCodeBody.RESP_SUCCED_CODE.getRespCode(),RespCodeBody.RESP_SUCCED_CODE.getRespDesc());
    }

    /**
     * 获取用户
     * @param phonenum 手机号
     * */
    public JSONObject getUser(String phonenum){

        System.out.printf("---------------"+phonenum);
       TUser tUser = tUserMapper.selecteTuser(phonenum);

        try {
            return MessageUntill.messageBody(Map_ObjectUntill.objectToMap(tUser),RespCodeBody.RESP_SUCCED_CODE.getRespCode(),RespCodeBody.RESP_SUCCED_CODE.getRespDesc());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return MessageUntill.messageBody(null,"0002","获取信息失败");
    }


}
